package com.wangzhen.spring.resource;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;

import java.io.IOException;

/**
 * 使用@Value注解，注入Resource对象
 */
public class ValueAnnotationInjectResourceDemo {

    /**
     * 使用@Value注解  加载单个文件
     */
    @Value("classpath:/META-INF/user.properties")
    private Resource userResource;

    /**
     * 使用@Value注解，加载多个资源文件（注意classpath 后面加星号，否则不生效）
     */
    @Value("classpath*:/META-INF/*.properties")
    private Resource[] addrResource;

    // 使用 List 或者Collection方式不行，看来只能使用数组的方式了
    /*@Value("classpath*:/META-INF/*.properties")
    private List<Resource> resourcesList;*/

    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ValueAnnotationInjectResourceDemo.class);
        context.refresh();

        ValueAnnotationInjectResourceDemo bean = context.getBean(ValueAnnotationInjectResourceDemo.class);
        System.out.println(IOUtils.readLines(bean.userResource.getInputStream()));
        System.out.println("----------");

        for (Resource resource : bean.addrResource) {
            System.out.println(IOUtils.readLines(resource.getInputStream()));
        }

        System.out.println("----------");

        /*for (Resource resource : bean.resourcesList) {
            System.out.println(IOUtils.readLines(resource.getInputStream()));
        }*/

        context.close();
    }
}
